/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package logging;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import protocol.TSServerInfo;

/**
 *
 * @author Tiago
 */
public class MasterKeyMapping extends KeyMapping<Integer,TSServerInfo>{

    private HashMap<Integer,TSServerInfo> mapping;
    private List<TableModelListener> listeners;

    private Iterator iterator;
    private int currentIndex;

    public MasterKeyMapping() {
        mapping = new HashMap<Integer, TSServerInfo>();
        listeners = new ArrayList<TableModelListener>();

        iterator = mapping.keySet().iterator();
        currentIndex = 0;

    }

    @Override
    public TSServerInfo get(Integer key) {
        return mapping.get(key);
    }

    @Override
    public TSServerInfo put(Integer key, TSServerInfo value) {
        TSServerInfo server = mapping.put(key, value);
        if( server == null ) return server;

        TableModelEvent e = new TableModelEvent(this);
        for( TableModelListener l : listeners ) {
            l.tableChanged(e);
        }

        return server;
    }

    @Override
    public void put(Map<Integer,TSServerInfo> values) {


        mapping.putAll(values);
        TableModelEvent e = new TableModelEvent(this);
        for( TableModelListener l : listeners ) {
            l.tableChanged(e);
        }

    }


    public int getRowCount() {
        return mapping.keySet().size();
    }

    public int getColumnCount() {
        return 2;
    }

    public String getColumnName(int columnIndex) {
        if( columnIndex == 0 ) return "Chave";
        else return "Servidor";
    }

    public Class<?> getColumnClass(int columnIndex) {
        if( columnIndex == 0) return Integer.class;
        else return String.class;
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {

        if( currentIndex > rowIndex ) {
            iterator = mapping.keySet().iterator();
            currentIndex = 0;
        }

        while( currentIndex < rowIndex ) {
            iterator.next();
            currentIndex++;
        }


        Object obj = null;
        if( columnIndex == 0 ) obj = iterator.next();
        else obj = mapping.get((Integer)iterator.next()).getUniqueID();
        currentIndex++;
        return obj;        

    }

    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        
    }

    public void addTableModelListener(TableModelListener l) {
        listeners.add(l);
    }

    public void removeTableModelListener(TableModelListener l) {
        listeners.remove(l);
    }


}
